{% extends 'base.html' %}
{% block title %}预测与推荐{% endblock %}
{% block nav %}预测与推荐{% endblock %}
{% block css %}
    <link href="../static/assets/css/visual2.css" rel="stylesheet"/>
{% endblock %}

{% block Sidebar %}
    <div class="sidebar" data-color="orange">
        <div class="logo">
            <a href="#" class="simple-text logo-mini">
                <img src="../static/assets/img/taobaologo.png" alt="#"/>
            </a>
            <a href="#" class="simple-text logo-normal">
                电商平台用户行为预测系统
            </a>
        </div>
        <div class="sidebar-wrapper">
            <ul class="nav">
                <li>
                    <a href="{{ url_for('ec.index') }}">
                        <i class="now-ui-icons design_app"></i>
                        <p>仪表盘</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.raw_data') }}">
                        <i class="now-ui-icons business_chart-pie-36"></i>
                        <p>原始数据</p>
                    </a>
                </li>
                <li class="active">
                    <a href="{{ url_for('ec.visual2') }}">
                        <i class="now-ui-icons education_atom"></i>
                        <p>预测与推荐</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.visual') }}">
                        <i class="now-ui-icons files_single-copy-04"></i>
                        <p>操作日志</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.user') }}">
                        <i class="now-ui-icons users_single-02"></i>
                        <p>个人中心</p>
                    </a>
                </li>
            </ul>
        </div>
    </div>
{% endblock %}

{% block content %}
    <div class="panel-header panel-header-sm"
         style="background: linear-gradient(135deg, #F5F5F5 0%, #1c84fc 100%);"></div>
    <div class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <!-- 用户行为预测 -->
                    <div class="col-lg-6 col-md-6">
                        <div class="card card-tasks">
                            <div class="card-header">
                                <h5 class="card-category">用户行为预测</h5>
                                <h4 class="card-title">预测选择</h4>
                            </div>
                            <div class="card-body">
                                <!-- 添加用户ID输入框 -->
                                <div class="form-group">
                                    <label for="userIdInput">用户ID</label>
                                    <input type="text" class="form-control" id="userIdInput" placeholder="请输入用户ID">
                                </div>
                                <!-- 添加预测算法选择 -->
                                <div class="form-group">
                                    <label for="predictionType">模型选择</label>
                                    <select id="modelSelector" class="form-control">
                                        <option value="DecisionTree">决策树</option>
                                        <option value="RandomForest">随机森林</option>
                                        <option value="LogisticRegression">逻辑回归</option>
                                    </select>
                                </div>
                                <!-- 添加预测类型选择 -->
                                <div class="form-group">
                                    <label for="predictionType">预测类型</label>
                                    <select id="predictionType" class="form-control">
                                        <option value="purchase_intent">购买意向预测</option>
                                        <option value="churn_risk">流失风险预测</option>
                                        <option value="repurchase">复购预测</option>
                                    </select>
                                </div>
                                <button id="predictButton" class="btn btn-primary mt-3">开始预测</button>

                                <!-- 预测结果展示 -->
                                <div id="predictionResult" class="mt-4" style="display: none;">
                                    <h5>预测结果</h5>
                                    <div id="resultContent"></div>

                                    <!-- 模型性能指标表格 -->
                                    <div class="mt-3">
                                        <h6>模型性能指标</h6>
                                        <table class="table table-bordered metrics-table">
                                            <thead class="thead-light">
                                            <tr>
                                                <th>指标</th>
                                                <th>值</th>
                                            </tr>
                                            </thead>
                                            <tbody id="metricsTable">
                                            <tr>
                                                <td>正确率 (Accuracy)</td>
                                                <td id="accuracy">--</td>
                                            </tr>
                                            <tr>
                                                <td>精度 (Precision)</td>
                                                <td id="precision">--</td>
                                            </tr>
                                            <tr>
                                                <td>召回率 (Recall)</td>
                                                <td id="recall">--</td>
                                            </tr>
                                            <tr>
                                                <td>F1分数 (F1-Score)</td>
                                                <td id="f1Score">--</td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <!-- 表单部分保持不变 ... -->

                                    <!-- 预测结果展示 -->
                                    <div id="predictionResult" class="mt-4" style="display: none;">
                                        <h5>预测结果</h5>
                                        <div id="resultContent"></div>
                                    </div>

                                    <!-- 删除这整个图表区域 -->
                                    <!-- <div class="chart-area mt-4">
                                        <canvas id="predictionChart"></canvas>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 个性化推荐 -->
                    <div class="col-lg-6 col-md-6">
                        <div class="card card-chart">
                            <div class="card-header">
                                <h5 class="card-category">个性化推荐</h5>
                                <h4 class="card-title">为您推荐</h4>
                            </div>
                            <div class="card-body">
                                <div id="recommendationInfo" class="mb-3"></div>
                                <div id="recommendationLoading" class="text-center" style="display: none;">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="sr-only">加载中...</span>
                                    </div>
                                    <p>正在为您生成个性化推荐...</p>
                                </div>
                                <div id="recommendationContainer">
                                    <div class="row" id="recommendedItems">
                                        <!-- 推荐商品将通过 JavaScript 动态添加 -->
                                    </div>
                                </div>
                                <div id="recommendationExplanation" class="mt-3 small text-muted"
                                     style="display: none;">
                                    <p><i class="now-ui-icons travel_info"></i> 推荐依据：基于您的浏览、收藏、加购和购买历史，结合相似用户偏好生成
                                    </p>
                                </div>

                                <!-- 推荐可信度分析 -->
                                <div class="row mt-3">
                                    <div class="col-md-12">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="card-title">推荐可信度分析</h6>
                                            </div>
                                            <div class="card-body">
                                                <div id="trustFactors">
                                                    <div class="row text-center">
                                                        <div class="col-md-3">
                                                            <div class="trust-factor">
                                                                <i class="now-ui-icons users_single-02 text-primary"></i>
                                                                <h5 id="similarUsers">--</h5>
                                                                <p>相似用户偏好</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="trust-factor">
                                                                <i class="now-ui-icons ui-2_favourite-28 text-info"></i>
                                                                <h5 id="behaviorMatch">--</h5>
                                                                <p>行为匹配度</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="trust-factor">
                                                                <i class="now-ui-icons shopping_tag-content text-success"></i>
                                                                <h5 id="categoryPreference">--</h5>
                                                                <p>品类偏好</p>
                                                            </div>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <div class="trust-factor">
                                                                <i class="now-ui-icons media-1_album text-warning"></i>
                                                                <h5 id="activityScore">--</h5>
                                                                <p>活跃度评分</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script>
        // 用户行为预测
        document.getElementById('predictButton').addEventListener('click', function () {
            const selectedModel = document.getElementById('modelSelector').value;
            const predictionType = document.getElementById('predictionType').value;
            const userId = document.getElementById('userIdInput').value;

            if (!userId) {
                alert("请输入用户ID");
                return;
            }

            // 显示加载状态
            const predictButton = document.getElementById('predictButton');
            predictButton.disabled = true;
            predictButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 预测中...';

            // 显示推荐加载状态
            document.getElementById('recommendationLoading').style.display = 'block';
            document.getElementById('recommendationContainer').style.display = 'none';
            document.getElementById('recommendationExplanation').style.display = 'none';

            // 发送预测请求
            fetch('/pr/predict', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    model: selectedModel,
                    prediction_type: predictionType,
                    user_id: userId
                }),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 恢复按钮状态
                    predictButton.disabled = false;
                    predictButton.innerHTML = '开始预测';
                    document.getElementById('recommendationLoading').style.display = 'none';

                    if (!data.success) {
                        console.error("Prediction failed:", data.message);
                        alert(`预测失败: ${data.message || '未知错误'}`);
                        return;
                    }

                    console.log("Received prediction data:", data);

                    // 显示预测结果
                    const predictionResult = document.getElementById('predictionResult');
                    const resultContent = document.getElementById('resultContent');

                    // 根据预测类型显示不同的结果
                    let resultText = '';
                    if (data.prediction_type === 'purchase_intent') {
                        resultText = `<div class="alert alert-success">
                    <i class="now-ui-icons ui-2_like"></i> <strong>购买意向预测</strong>
                    <p class="mb-0">${data.metrics ? `预测准确率: ${(data.metrics.accuracy * 100).toFixed(2)}%` : '数据不足，无法计算准确率'}</p>
                    <p class="mb-0">该用户有${data.prediction_result ? '高' : '低'}购买意向</p>
                </div>`;
                    } else if (data.prediction_type === 'repurchase') {
                        resultText = `<div class="alert alert-${data.prediction_result ? 'success' : 'warning'}">
                    <i class="now-ui-icons shopping_delivery-fast"></i> <strong>复购预测</strong>
                    <p class="mb-0">${data.metrics ? `预测准确率: ${(data.metrics.accuracy * 100).toFixed(2)}%` : '数据不足，无法计算准确率'}</p>
                    <p class="mb-0">该用户${data.prediction_result ? '可能' : '不太可能'}会复购</p>
                </div>`;
                    } else if (data.prediction_type === 'churn_risk') {
                        resultText = `<div class="alert alert-${data.prediction_result ? 'danger' : 'success'}">
                    <i class="now-ui-icons ui-1_simple-remove"></i> <strong>流失风险预测</strong>
                    <p class="mb-0">该用户${data.prediction_result ? '有' : '无'}流失风险</p>
                </div>`;
                    }

                    resultContent.innerHTML = resultText;
                    predictionResult.style.display = 'block';

                    // 更新模型性能指标
                    updateMetrics(data.metrics);

                    // 更新可信度指标
                    updateTrustFactors(data);

                    // 显示推荐商品
                    displayRecommendedItems(data.recommended_items || [], data.prediction_type, data.prediction_result, data.metrics);
                })
                .catch(error => {
                    console.error("Error fetching prediction data:", error);
                    predictButton.disabled = false;
                    predictButton.innerHTML = '开始预测';
                    document.getElementById('recommendationLoading').style.display = 'none';
                    alert(`预测请求失败: ${error.message}`);
                });
        });

        // 更新模型性能指标
        function updateMetrics(metrics) {
            if (metrics) {
                document.getElementById('accuracy').textContent = metrics.accuracy ? metrics.accuracy.toFixed(4) : '--';
                document.getElementById('precision').textContent = metrics.precision ? metrics.precision.toFixed(4) : '--';
                document.getElementById('recall').textContent = metrics.recall ? metrics.recall.toFixed(4) : '--';
                document.getElementById('f1Score').textContent = metrics.f1_score ? metrics.f1_score.toFixed(4) : '--';
            } else {
                document.getElementById('accuracy').textContent = '--';
                document.getElementById('precision').textContent = '--';
                document.getElementById('recall').textContent = '--';
                document.getElementById('f1Score').textContent = '--';
            }
        }


        // 显示推荐商品
        function displayRecommendedItems(items, predictionType, predictionResult, metrics) {
            const recommendedItems = document.getElementById('recommendedItems');
            const recommendationInfo = document.getElementById('recommendationInfo');
            const recommendationExplanation = document.getElementById('recommendationExplanation');

            // 隐藏加载状态，显示推荐容器
            document.getElementById('recommendationLoading').style.display = 'none';
            document.getElementById('recommendationContainer').style.display = 'block';

            recommendedItems.innerHTML = ''; // 清空之前的推荐列表
            recommendationExplanation.style.display = 'none';

            // 根据预测类型显示不同的推荐信息
            // 根据预测类型显示不同的推荐信息
            if (predictionType === 'churn_risk') {
                if (predictionResult) {
                    recommendationInfo.innerHTML = `
                <div class="alert alert-danger">
                    <i class="now-ui-icons ui-2_settings-90"></i> <strong>流失风险预测</strong>
                    <p class="mb-0">系统检测到该用户有流失风险，建议采取挽留措施。</p>
                </div>
            `;
                } else {
                    recommendationInfo.innerHTML = `
                <div class="alert alert-success">
                    <i class="now-ui-icons ui-2_settings-90"></i> <strong>流失风险预测</strong>
                    <p class="mb-0">该用户目前无流失风险。</p>
                </div>
            `;
                }
            } else if (predictionType === 'repurchase' && !predictionResult) {
                recommendationInfo.innerHTML = `
            <div class="alert alert-warning">
                <i class="now-ui-icons ui-1_simple-remove"></i> <strong>复购可能性低</strong>
                <p class="mb-0">${metrics ? `预测准确率: ${(metrics.accuracy * 100).toFixed(2)}%` : '数据不足，无法计算准确率'}</p>
                <p class="mb-0">根据分析，该用户近期复购可能性较低，暂不推荐商品。</p>
            </div>
        `;
            } else if ((predictionType === 'purchase_intent' || predictionType === 'repurchase') && items && items.length > 0) {
                recommendationInfo.innerHTML = `
            <div class="alert alert-success">
                <i class="now-ui-icons ui-2_like"></i> <strong>为您精心挑选</strong>
                <p class="mb-0">${metrics ? `基于预测结果（准确率: ${(metrics.accuracy * 100).toFixed(2)}%），以下商品可能符合您的兴趣` : '基于您的行为数据，以下商品可能符合您的兴趣'}</p>
            </div>
        `;

                // 显示推荐解释
                recommendationExplanation.style.display = 'block';

                // 创建商品卡片
                items.forEach((item) => {
                    const col = document.createElement('div');
                    col.className = 'col-md-6 mb-3';
                    col.innerHTML = `
                <div class="card h-100 recommendation-card">
                    <div class="card-header p-2 text-center">
                        <span class="badge badge-primary">推荐度 ${item.recommendation_score.toFixed(1)}%</span>
                    </div>
                    <img src="${item.image_url}" class="card-img-top" alt="商品图片"
                         onerror="this.src='../static/assets/img/default-product.png'">
                    <div class="card-body p-2">
                        <h6 class="card-title">商品 #${item.item_id}</h6>
                        <p class="card-text small text-muted">
                            <i class="now-ui-icons ui-2_favourite-28"></i>
                            相似用户购买率 ${item.buy_rate ? item.buy_rate.toFixed(1) : 0}%
                        </p>
                    </div>
                    <div class="card-footer p-2 bg-white">
                        <button class="btn btn-sm btn-block btn-primary">查看详情</button>
                    </div>
                </div>
            `;
                    recommendedItems.appendChild(col);
                });
            } else {
                recommendationInfo.innerHTML = `
            <div class="alert alert-secondary">
                <i class="now-ui-icons ui-1_zoom-bold"></i> <strong>暂无推荐商品</strong>
                <p class="mb-0">系统暂时没有找到适合您的推荐商品。</p>
            </div>
        `;
            }
        }

        // 更新可信度指标
        function updateTrustFactors(data) {
            if (data.trust_factors) {
                document.getElementById('similarUsers').textContent = `${data.trust_factors.similar_users}%`;
                document.getElementById('behaviorMatch').textContent = `${data.trust_factors.behavior_match.toFixed(1)}%`;
                document.getElementById('categoryPreference').textContent = `${data.trust_factors.category_preference.toFixed(1)}%`;
                document.getElementById('activityScore').textContent = `${data.trust_factors.activity_score.toFixed(1)}%`;
            }
        }
    </script>
{% endblock %}